<template>
    <div class="collect-list-container">
        <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
            <a-tab-pane key="posts">
                <template #tab>
                    <span>
                        <icon class="anticon">
                            <template #component>
                                <svg width="1em" height="1em" fill="currentColor" t="1734583509299" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="1504" >
                                    <path
                                        d="M708.9 393.2H329.1c-19.9 0-36.1 16.3-36.1 36.1 0 19.9 16.3 36.1 36.1 36.1h379.7c19.9 0 36.1-16.3 36.1-36.1 0.1-19.8-16.2-36.1-36-36.1zM323.1 627.1h379.7c19.9 0 36.1-16.3 36.1-36.1 0-19.9-16.3-36.1-36.1-36.1H323.1c-19.9 0-36.1 16.3-36.1 36.1s16.3 36.1 36.1 36.1zM702.9 716.4H323.1c-19.9 0-36.1 16.3-36.1 36.1 0 19.9 16.3 36.1 36.1 36.1h379.7c19.9 0 36.1-16.3 36.1-36.1 0.1-19.8-16.2-36.1-36-36.1z"
                                        p-id="1505" ></path>
                                    <path
                                        d="M789.7 64.2H426.8v0.5c-11.8-1.8-23.8 1.7-32.9 10L173.4 277.3c-9.6 8.8-13.8 21.4-11.9 33.7h-0.5v572.6c0 42 33.8 76.2 75.3 76.2h553.4c41.5 0 75.3-34.2 75.3-76.2V140.4c0-42-33.8-76.2-75.3-76.2zM194.8 307.3c-0.6-1.4-1.1-4 1.4-6.3L416.8 98.3c1.3-1.2 2.7-1.6 3.9-1.6 1 0 1.9 0.3 2.5 0.5 1.3 0.6 3.6 2 3.6 5.3V305c0 3.2-2.7 5.9-6 5.9H200.3c-3.5 0.1-4.9-2.2-5.5-3.6z m627 576.3c0 17.9-14.4 32.5-32.1 32.5H236.3c-17.7 0-32.1-14.6-32.1-32.5V362.3c0-10.4 8.4-18.8 18.8-18.8h197.8c21.7 0 39.4-17.2 39.4-38.4V126.7c0-10.4 8.4-18.8 18.8-18.8h310.7c17.7 0 32.1 14.6 32.1 32.5v743.2z"
                                        p-id="1506" ></path>
                                </svg>
                            </template>
                        </icon>
                        帖子收藏
                    </span>
                </template>
                <!-- 帖子收藏列表 -->
                <div class="table-container">
                    <a-skeleton active :loading="loading">
                        <template #default>
                            <a-table
                                :columns="postsColumns"
                                :data-source="userCollectPostsList"
                                :pagination="pagination"
                                bordered
                                @change="handleTableChange"
                            >
                                <template #bodyCell="{ column, record }">
                                    <template v-if="column.key === 'title'">
                                        <router-link 
                                            :to="{path: '/social/detail', query:{ postId: record.postId }}"
                                            class="post-title-link"
                                        >
                                            {{ record.title }}
                                        </router-link>
                                    </template>
                                    
                                    <template v-if="column.key === 'content'">
                                        <router-link 
                                            :to="{path: '/social/detail', query:{ postId: record.postId }}"
                                            class="post-content-link"
                                        >
                                            <div class="post-content" v-html="truncateContent(sanitizeHtml(record.content), 50)"></div>
                                        </router-link>
                                    </template>

                                    <template v-if="column.key === 'tags'">
                                        <div class="tags-container">
                                            <a-tag 
                                                v-for="tag in record.tags" 
                                                :key="tag"
                                                color="blue"
                                            >
                                                {{ tag }}
                                            </a-tag>
                                        </div>
                                    </template>

                                    <template v-if="column.key === 'editTime'">
                                        {{ formatDate(record.editTime) }}
                                    </template>

                                    <template v-if="column.key === 'action'">
                                        <a-button 
                                            type="link" 
                                            danger 
                                            :loading="loading" 
                                            @click="handleUnCollectPost(record)"
                                        >
                                            取消收藏
                                        </a-button>
                                    </template>
                                </template>
                            </a-table>
                        </template>
                        <template #avatar>
                            <a-skeleton-element active type="button" />
                        </template>
                    </a-skeleton>
                </div>
            </a-tab-pane>
            <a-tab-pane key="fishSite">
                <template #tab>
                    <span>
                        <icon class="anticon anticon-apple">
                            <template #component>
                                <svg width="1em" height="1em" fill="currentColor" t="1734583704701" class="icon"
                                    viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                                    p-id="2866">
                                    <path
                                        d="M505.563429 133.851429a427.066514 427.066514 0 0 1 308.721371 225.192228l3.832686 7.606857 3.306057 6.904686L1024 272.296229v479.407542l-202.576457-101.288228-3.306057 6.933943a426.861714 426.861714 0 0 1-366.357943 238.328685l-8.513829 0.234058-8.250514 0.087771c-215.478857 0-396.112457-160.533943-423.204571-371.9168l-0.877715-7.402057-0.526628-4.681143 1.375085-12.0832a423.877486 423.877486 0 0 1 67.3792-180.867657l-0.4096 2.048a213.577143 213.577143 0 0 1 209.276343-171.739429 213.313829 213.313829 0 0 1 213.313829 213.284572 213.284571 213.284571 0 0 1-207.345372 213.284571l-5.968457 0.058514v-85.313828a128 128 0 1 0-125.571657-153.014857l-1.053257 6.144-0.877714 7.460571 0.2048 0.087772a339.002514 339.002514 0 0 0-63.780572 155.648l-0.643657 5.12 0.292572 2.2528c21.562514 163.664457 158.368914 289.060571 323.935085 295.994514l7.314286 0.2048 7.168 0.087771c145.261714 0 272.9984-91.574857 321.243429-225.6896l2.428342-6.9632 15.623315-46.548114 164.366628 82.183314v-203.307885l-164.366628 82.212571-15.623315-46.518857a341.577143 341.577143 0 0 0-264.367542-227.5328l11.264-84.640914z m-174.8992 186.133942v85.343086H245.321143v-85.343086h85.343086z"
                                        p-id="2867"></path>
                                </svg>
                            </template>
                        </icon>
                        钓场收藏
                    </span>
                </template>
                <div class="table-container">
                    <a-skeleton active :loading="loading">
                        <template #default>
                            <a-table
                                :columns="fishSiteColumns"
                                :data-source="userCollectFishSiteList"
                                :pagination="pagination"
                                bordered
                                @change="handleTableChange"
                            >
                                <template #bodyCell="{ column, record }">
                                    <template v-if="column.key === 'name'">
                                        <router-link 
                                            :to="{ 
                                                path: `/angling/detail/${record.fishSiteId}`,
                                            }"
                                            
                                        >
                                            {{ record.name }}
                                        </router-link>
                                    </template>
                                    <template v-if="column.key === 'address'">
                                        {{ record.province + record.city + record.address }}
                                    </template>
                                    <template v-if="column.key === 'avgRating'">
                                        <span>{{ record.avgRating ? record.avgRating : '暂无评分' }}</span>
                                    </template>
                                    <template v-if="column.key === 'feeType'">
                                        <span>{{ record.feeType === 'Y' ? '收费 ' : '免费' }}</span>
                                    </template>
                                    <template v-if="column.key === 'amount'">
                                        <span>{{ record.amount ? record.amount : '暂无金额' }}</span>
                                    </template>
                                    <template v-if="column.key === 'action'">
                                        <a-button 
                                            type="link" 
                                            danger 
                                            :loading="loading" 
                                            @click="handleUnCollect(record)"
                                        >
                                            取消收藏
                                        </a-button>
                                    </template>
                                </template>
                            </a-table>
                        </template>
                        <template #avatar>
                            <a-skeleton-element active type="button" />
                        </template>
                    </a-skeleton>
                </div>
            </a-tab-pane>
        </a-tabs>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { userStore } from '@/store/modules/UserStore';
import Icon from '@ant-design/icons-vue';
import DOMPurify from 'dompurify';
import { message } from 'ant-design-vue';
import { AnglingVO } from '@/api/front/angling/types';
import { PostsVO } from '@/api/front/social/types';
import { collectPosts, userCollectPosts } from '@/api/front/social';
import { anglingUserCollectList } from '@/api/front/angling';
import { debounce } from 'lodash-es';
import { collectFishSite } from '@/api/front/collect';

const route = useRoute();
const activeKey = ref('posts');
const loading = ref(false);

const userCollectPostsList = ref<PostsVO[]>([])
const userCollectFishSiteList = ref<AnglingVO[]>([])

// 帖子列表的列配置
const postsColumns = [
    {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: '40%',
    },
    {
        title: '标签',
        dataIndex: 'tags',
        key: 'tags',
        width: '15%',
    },
    {
        title: '收藏时间',
        dataIndex: 'editTime',
        key: 'editTime',
        width: '12%',
    },
    {
        title: '操作',
        key: 'action',
        width: '13%',
    }
];

// 钓点列表的列配置
const fishSiteColumns = [
    {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: '10%',
        ellipsis: true,
    },
    {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
        width: '20%',
        ellipsis: true,
    },
    {
        title: '收费类型',
        dataIndex: 'feeType',
        key: 'feeType',
        width: '10%',
    },
    {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
        width: '10%',
    },
    {
        title: '评分',
        dataIndex: 'avgRating',
        key: 'avgRating',
        width: '10%',
    },
    {
        title: '操作',
        key: 'action',
        width: '20%',
    }
   
];

const pagination = {
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: false,
    showTotal: (total: number) => `共 ${total} 条`
};

const handleTableChange = (pag: any) => {
    pagination.current = pag.current;
    getList(activeKey.value)
};

const handleTabChange = (key: string) => {
    activeKey.value = key
    getList(activeKey.value)
}

// 内容截断
const truncateContent = (content: string, maxLength: number) => {
    const tempElement = document.createElement('div');
    tempElement.innerHTML = content;
    const text = tempElement.innerText || tempElement.textContent;

    return text.length > maxLength
        ? text.slice(0, maxLength) + '...'
        : text;
};

// HTML 净化
const sanitizeHtml = (content: string) => {
    return DOMPurify.sanitize(content);
};

// 日期格式化
const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 取消收藏帖子（���加防抖）
const handleUnCollectPost = debounce(async (record: PostsVO) => {
    try {
        loading.value = true;
        // TODO: 调用取消收藏接口
        await collectPosts({
            postsId: record.postId,
            type: 'uncollect',
            authorId: record.userId
        });
        message.success('取消收藏成功');
        // 重新加载列表
        await getList(activeKey.value);
    } finally {
        loading.value = false;
    }
}, 500);

// 取消收藏钓点（添加防抖）
const handleUnCollect = debounce(async (fishSite: AnglingVO) => {
    try {
        loading.value = true;
        await collectFishSite({
            type: 'uncollect',
            fishSiteId: fishSite.fishSiteId,
            authorId: fishSite.userId
        })
        message.success('取消收藏成功');
        // 重新加载列表
        await getList(activeKey.value);
    }finally {
        loading.value = false;
    }
}, 500);

// 获取列表数据
const getList = async (type: string) => {
    loading.value = true;
    try {
        if(type === 'posts'){
            const res = await userCollectPosts({pageNum:pagination.current, pageSize:pagination.pageSize})
            userCollectPostsList.value = res.data.rows
            pagination.total = res.data.total
        } else if(type === 'fishSite'){
            const res = await anglingUserCollectList({pageNum:pagination.current, pageSize:pagination.pageSize})
            userCollectFishSiteList.value = res.data.rows
            pagination.total = res.data.total
        }
    } catch (error) {
        message.error('获取数据失败');
    } finally {
        // 添加延迟以使动画更流畅
        setTimeout(() => {
            loading.value = false;
        }, 300);
    }
}

// 暴露切换标签页的方法
const switchTab = (type: string) => {
  activeKey.value = type;
  // 切换标签页后重新加载数据
  getList(type);
};

// 暴露方法给父组件
defineExpose({
  switchTab
});

onMounted(() => {
    if (route.params.type) {
        activeKey.value = route.params.type as string;
    }
    getList(activeKey.value)
});
</script>

<style lang="scss" scoped>
.collect-list-container {
    padding: 24px;
    
    .post-title-link {
        font-weight: 500;
        color: #262626;
        text-decoration: none;
        
        &:hover {
            color: #1890ff;
        }
    }
    
    .post-content-link {
        text-decoration: none;
        
        &:hover {
            .post-content {
                color: #1890ff;
            }
        }
        
        .post-content {
            color: #595959;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            transition: color 0.3s;
        }
    }
    
    .tags-container {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
        
        :deep(.ant-tag) {
            margin: 0;
            cursor: default;
            
            &:hover {
                opacity: 0.85;
            }
        }
    }
    
    :deep(.ant-table-thead > tr > th) {
        background: #fafafa;
        font-weight: 500;
    }
    
    :deep(.ant-table-tbody > tr > td) {
        vertical-align: top;
    }
    
    .table-container {
        position: relative;
        min-height: 200px;
        
        // 添加过渡动画
        :deep(.ant-skeleton) {
            &.ant-skeleton-active {
                .ant-skeleton-content {
                    .ant-skeleton-title,
                    .ant-skeleton-paragraph > li {
                        background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
                        background-size: 400% 100%;
                        animation: ant-skeleton-loading 1.4s ease infinite;
                    }
                }
            }
        }
        
        :deep(.ant-table-wrapper) {
            transition: opacity 0.3s ease;
            opacity: 1;
        }
        
        &.loading {
            :deep(.ant-table-wrapper) {
                opacity: 0;
            }
        }
    }
}

@keyframes ant-skeleton-loading {
    0% {
        background-position: 100% 50%;
    }
    100% {
        background-position: 0 50%;
    }
}
</style>
